package cn.openea.perpartner.cms.utils;

import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.properties.TextAlignment;
import lombok.AllArgsConstructor;
import lombok.Data;

import javax.swing.*;
import java.awt.*;

/**
 * @Name: 文本水设置印类
 * @desc:
 * @author: Mr.Yun
 * @Created: 2022/8/27 11:24
 */
@Data
@AllArgsConstructor
public class TextWaterMarkHandler implements IEventHandler {
    // 水印文字
    private String waterMarkContent;
    // 水印字体
    private PdfFont pdfFont;

    @Override
    public void handleEvent(com.itextpdf.kernel.events.Event event) {
        PdfDocumentEvent documentEvent = (PdfDocumentEvent) event;
        PdfPage page = documentEvent.getPage();
        com.itextpdf.kernel.geom.Rectangle pageSize = page.getPageSize();
        JLabel label = new JLabel();
        label.setText(this.waterMarkContent);
        FontMetrics metrics = label.getFontMetrics(label.getFont());
        int textHeight = metrics.getHeight();
        int textWidth = metrics.stringWidth(label.getText());

        //Canvas对象过期了，可以使用Document对象
        Document document = new Document(documentEvent.getDocument()).setFont(pdfFont).setFontSize(33);//设置字体和字体大小
        document.setFontColor(new DeviceRgb(Color.LIGHT_GRAY));//设置字体颜色

        //循环添加水印-posX表示横向起始位置，从左向右。posY表示纵向起始位置，从下到上。
        for (float posX = 130f; posX < pageSize.getWidth(); posX = posX + textWidth * 5) {
            for (float posY = 70f; posY < pageSize.getHeight(); posY = posY + textHeight * 15) {
                document.showTextAligned(this.waterMarkContent, posX, posY, TextAlignment.CENTER, 145f);
            }
        }
    }
}
